<?php

namespace App\Http\Controllers\common;

use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//角色模型
use App\Models\Role;
//地址模型
use App\Models\Area;
use App\Models\Building;
use App\Models\Room;
use App\Models\Member;
use App\Models\Areamember;
use App\Models\Buildingmember;
use App\Models\Roommember;
//设备模型
use App\Models\Type;
use App\Models\Device;

class PublicController extends Controller
{
    //代理商id
    protected $agent_id;
    protected $role_id;
    protected $area_ids;
    protected $auth_ids;
    protected $where = '';

    public function __construct(Request $request)
    {
        $this -> agent_id = $request->input('agent_id',$request -> cookie('logon')['agent_id']);
        $this -> role_id = $request -> cookie('logon')['role_id'];
        $this -> area_ids = Role::find($this->role_id)?Role::find($this->role_id) -> area_ids:'';
        $this -> auth_ids = Role::find($this->role_id)?Role::find($this->role_id) -> auth_ids:'';
    }

    //获取代理商下的所有服务范围
    public function rangeInfo($range,$get=[]){
        //获取角色所管理的区域
        switch ($range){
            case 'area':
                if($this -> area_ids === '0'){
                    eval('$rangeInfo = DB::table("area") 
                    -> where("area.agent_id",$this-> agent_id)
                    '.$this -> where.' 
                    -> paginate(10);');
                }else{
                    eval('$rangeInfo = DB::table("area") 
                    -> where("area.agent_id",$this -> agent_id)
                    '.$this -> where.'
                    -> whereIn("area.id",explode(",",$this -> area_ids))
                    -> paginate(10);');
                }
                break;
            case 'building':
                if($this -> area_ids === '0'){
                    eval('$rangeInfo = DB::table("building") 
                    -> leftJoin("area","building.area_id","=","area.id") 
                    -> select("building.*","building.area_id","area.name as area_name") 
                    -> where("building.agent_id",$this -> agent_id)
                    '.$this -> where.'
                    -> paginate(10);');
                }else{
                    eval('$rangeInfo = DB::table("building") 
                    -> leftJoin("area","building.area_id","=","area.id") 
                    -> select("building.*","building.area_id","area.name as area_name") 
                    -> where("building.agent_id",$this -> agent_id)
                    '.$this -> where.'
                    -> whereIn("area.id",explode(",",$this -> area_ids))
                    -> paginate(10);');
                }
                break;
            case 'room':
                if($this -> area_ids === '0'){
                    eval('$rangeInfo = DB::table("room") 
                    -> leftJoin("building","room.building_id","=","building.id") 
                    -> leftJoin("area","building.area_id","=","area.id") 
                    -> select("room.*","room.building_id","building.name as building_name","building.area_id","area.name as area_name") 
                    -> where("room.agent_id",$this -> agent_id)
                    '.$this -> where.' 
                    -> paginate(10);');
                }else{
                    eval('$rangeInfo = DB::table("room") 
                    -> leftJoin("building","room.building_id","=","building.id") 
                    -> leftJoin("area","building.area_id","=","area.id") 
                    -> select("room.*","room.building_id","building.name as building_name","building.area_id","area.name as area_name") 
                    -> where("room.agent_id",$this -> agent_id)
                    '.$this -> where.'
                    -> whereIn("area.id",explode(",",$this -> area_ids))
                    -> paginate(10);');
                }
                break;
            default:
                $rangeInfo = [];
        }
        return $rangeInfo;
    }

    //获取包含负责人的服务范围信息或单个范围的负责人
    public function memberInRange($range,$rangeInfo){
        $rangeObj = $this -> rangeObj($range)['rangeObj'];
        if($rangeObj){
            if(is_array($rangeInfo)){
                foreach ($rangeInfo as $key=>$val){
                    //获取指定区域下的管理员信息
                    $members = $rangeObj -> find($val['id']);
                    if($members&&$members->member){
                        $member_info = $members -> member() -> select('name','phone') -> get() -> toarray();
                        $rangeInfo[$key]['member'] = $member_info;
                    }
                }
                return $rangeInfo;
            }else{
                $members = $rangeObj -> find($rangeInfo);
                if($members&&$members->member){
                    $member_info = $rangeObj -> find($rangeInfo) -> member() -> select('name','phone') -> get() -> toarray();
                    return $member_info;
                }else{
                    return [];
                }
            }
        }else{
            return NULL;
        }
    }

    //追加负责人
    public function addMember($range,$area_id,$member){
        $touchObj = $this -> rangeObj($range)['touchObj'];
        if($touchObj){
            //查询member表
            $member_res = Member::where('name',$member) ->select('id') -> first();
            if($member_res){
                $member_arr = $member_res -> toarray();
                $member_id = $member_arr['id'];
                //查询区域和客户的关系表
                $condition = $touchObj->where([$range.'_id'=>$area_id,'member_id'=>$member_id]) -> first();
                if(!$condition){
                    //插入区域和客户的关系表
                    $res = $touchObj->create([$range.'_id' => $area_id,'member_id'=>$member_id]);
                    if($res){
                        $info['status'] = 1;
                        $info['member_id'] = $member_id;
                    }else{
                        $info['status'] = -1;
                    }
                }else{
                    $info['status'] = -1;
                }
            }else{
                $info['status'] = -1;
            }
        }else{
            $info['status'] = -1;
        }
        return $info;
    }

    //删除负责人
    public function delMember($range,$area_id,$member_id){
        $touchObj = $this -> rangeObj($range)['touchObj'];
        if($touchObj){
            //查询区域和客户的关系表并删除
            $res = $touchObj -> where([$range.'_id'=>$area_id,'member_id'=>$member_id]) -> delete();
            if($res){
                $info['status'] = 1;
            }else{
                $info['status'] = -1;
            }
        }else{
            $info['status'] = -1;
        }
        return $info;
    }

    //获取服务范围对象
    public function rangeObj($range){
        switch ($range){
            case 'area':
                $obj['rangeObj'] = new Area();
                $obj['touchObj'] = new Areamember();
                break;
            case 'building':
                $obj['rangeObj'] = new Building();
                $obj['touchObj'] = new Buildingmember();
                break;
            case 'room':
                $obj['rangeObj'] = new Room();
                $obj['touchObj'] = new Roommember();
                break;
            default :
                $obj = NULL;
        }
        return $obj;
    }
    /*地址管理末*/

    /*设备管理始*/
    //获取lora设备信息
    public function deviceInfo($type_id,$get){
        $db = $this -> typeDB($type_id);
        if($db){
            $info = '';
            if($this -> area_ids === '0'){
                eval('$info = DB::table($db)
                -> leftJoin("room",$db.".room_id","=","room.id")
                -> leftJoin("building","room.building_id","=","building.id")
                -> leftJoin("area","building.area_id","=","area.id")
                -> leftJoin("model",$db.".model_id","=","model.id")
                -> select($db.".*","room.name as room_name","room.building_id","building.name as building_name","building.area_id","area.name as area_name","model.name as model_name") 
                -> where($db.".agent_id",$this -> agent_id)'
                .$this->where.
                '-> paginate(10);');
            }else{
                eval('$info = DB::table($db)
                -> leftJoin("room",$db.".room_id","=","room.id")
                -> leftJoin("building","room.building_id","=","building.id")
                -> leftJoin("area","building.area_id","=","area.id")
                -> leftJoin("model",$db.".model_id","=","model.id")
                -> select($db.".*","room.name as room_name","room.building_id","building.name as building_name","building.area_id","area.name as area_name","model.name as model_name") 
                -> where($db.".agent_id",$this -> agent_id)
                ' .$this -> where.'
                -> whereIn("area.id",explode(",",$this -> area_ids))
                -> paginate(10);');
            }
            $data = $info -> all();
            foreach ($data as $key=>$val){
                $areaMember = '';
                $buildingMember = '';
                $roomMember = '';
                $areaMemberArr = $this -> memberInRange('area',$data[$key]['area_id']);
                $buildingMemberArr = $this -> memberInRange('building',$data[$key]['building_id']);
                $roomMemberArr = $this -> memberInRange('room',$val['room_id']);
                if(!empty($areaMemberArr)){
                    foreach($areaMemberArr as $v){
                        $areaMember .= $v['name'].',';
                    }
                }
                if(!empty($buildingMemberArr)) {
                    foreach ($buildingMemberArr as $v) {
                        $buildingMember .= $v['name'] . ',';
                    }
                }
                if(!empty($roomMemberArr)) {
                    foreach ($roomMemberArr as $v) {
                        $roomMember .= $v['name'] . ',';
                    }
                }
                $data[$key]['member'] = array(
                    'area'=>substr($areaMember,0,-1),
                    'building'=>substr($buildingMember,0,-1),
                    'room'=>substr($roomMember,0,-1)
                );
            }
        }
        return ['data'=>$data,'info'=>$info];
    }
    //获取nb设备信息
    public function nbdevInfo($get){
            $info = '';
            if($this -> area_ids === '0'){
                eval('$info = DB::table("nb_bind as nb")
                -> leftJoin("room","nb.room_id","=","room.id")
                -> leftJoin("building","room.building_id","=","building.id")
                -> leftJoin("area","building.area_id","=","area.id")
                -> select("nb.*","room.name as room_name","room.building_id","building.name as building_name","building.area_id","area.name as area_name") 
                -> where("nb.agent_id",$this -> agent_id)'
                .$this->where.
                '-> paginate(10);');
            }else{
                eval('$info = DB::table("nb_bind as nb")
                -> leftJoin("room","nb.room_id","=","room.id")
                -> leftJoin("building","room.building_id","=","building.id")
                -> leftJoin("area","building.area_id","=","area.id")
                -> select("nb.*","room.name as room_name","room.building_id","building.name as building_name","building.area_id","area.name as area_name") 
                -> where("nb.agent_id",$this -> agent_id)
                '.$this->where.'
                -> whereIn("area.id",explode(",",$this -> area_ids)) 
                -> paginate(10);');
            }
            $data = $info -> all();
            foreach ($data as $key=>$val){
                $areaMember = '';
                $buildingMember = '';
                $roomMember = '';
                $areaMemberArr = $this -> memberInRange('area',$data[$key]['area_id']);
                $buildingMemberArr = $this -> memberInRange('building',$data[$key]['building_id']);
                $roomMemberArr = $this -> memberInRange('room',$val['room_id']);
                if(!empty($areaMemberArr)){
                    foreach($areaMemberArr as $v){
                        $areaMember .= $v['name'].',';
                    }
                }
                if(!empty($areaMemberArr)) {
                    foreach ($buildingMemberArr as $v) {
                        $buildingMember .= $v['name'] . ',';
                    }
                }
                if(!empty($roomMemberArr)) {
                    foreach ($roomMemberArr as $v) {
                        $roomMember .= $v['name'] . ',';
                    }
                }
                $data[$key]['member'] = array(
                    'area'=>substr($areaMember,0,-1),
                    'building'=>substr($buildingMember,0,-1),
                    'room'=>substr($roomMember,0,-1)
                );
            }
        return ['data'=>$data,'info'=>$info];
    }
    //将设备添加到lora
    public function addDevice($type_id,$DevEUI){
        //查询设备表
        $device = Device::where('DevEUI',$DevEUI) -> select('DevEUI','DevAddr','NwkSKey','AppSKey') -> first();
        //查询设备类型表
        $AppEUI = Type::find($type_id) -> AppEUI;
        //将设备添加到lora
        $lora = new LoraController();
        $output = $lora -> addTerminal($device->DevEUI,$AppEUI,$device->DevAddr,$device->NwkSKey,$device->AppSKey);
        return $output;
    }

    //将设备从lora删除
    public function delDevice($DevEUI){
        $lora = new LoraController();
        $output = $lora -> delTerminal($DevEUI);
        return $output;
    }

    //获取设备类型对象
    public function typeDB($type_id){
        switch ($type_id){
            case 2:
                $db = 'smoke';
                break;
            case 3:
                $db = 'infrared';
                break;
            case 5:
                $db = 'help';
                break;
            case 6:
                $db = 'gas';
                break;
            case 7:
                $db = 'gateway';
                break;
            case 9:
                $db = 'electric';
                break;
            default :
                $db = NULL;
        }
        return $db;
    }
    /*设备管理末*/

    //权限表数据
    public function authInfo($gadget=false){
        $where = [];
        $where['level'] = 1;
        //判断是否是内部用户
        if($this->agent_id != 1){
            $where['limit'] = 1;
        }
        //判断模块是否在侧边栏显示
        if($gadget){
            $where['gadget'] = 1;
        }
        if($this -> auth_ids === '0'){
            $info = DB::table('auth as a')
                -> leftJoin('icon as i','a.icon_id','=','i.id')
                -> select('a.id','a.title','i.icon','a.href','a.spread','a.module')
                -> where($where)
                -> orderBy('module','asc')
                -> get();
            $where['level'] = 2;
            foreach ($info as $key=>$val){
                $info[$key]['children'] = DB::table('auth as a')
                    -> leftJoin('icon as i','a.icon_id','=','i.id')
                    -> select('a.id','a.title','i.icon','a.href','a.spread','a.module')
                    -> where($where)
                    -> where('module',$val['module'])
                    -> get();
            }
        }else{
            $info = DB::table('auth as a')
                -> leftJoin('icon as i','a.icon_id','=','i.id')
                -> select('a.id','a.title','i.icon','a.href','a.spread','a.module')
                -> where($where)
                -> whereIn('a.id',explode(',',$this -> auth_ids))
                -> orderBy('module','asc')
                -> get();
            $where['level'] = 2;
            foreach ($info as $key=>$val){
                $info[$key]['children'] = DB::table('auth as a')
                    -> leftJoin('icon as i','a.icon_id','=','i.id')
                    -> select('a.id','a.title','i.icon','a.href','a.spread','a.module')
                    -> where($where)
                    -> whereIn('a.id',explode(',',$this -> auth_ids))
                    -> where('module',$val['module'])
                    -> get();
            }
        }
        return $info;
    }
    /*************代理商信息处理域*************/
    //获取旗下代理商id
    static public function getAgent($agentId,&$brr=[]){

        $arr = DB::table('agent') -> where(['pid'=>$agentId]) -> get();
        if($arr != null){
            foreach ($arr as $v){
                $brr[] = $v;
                self::getAgent($v['id'],$brr);
            }
        }
        return $brr;
    }

    //将自身数据信息放入数组
    public function allAgent($agentId){
        $agent = [];
        $brr = self::getAgent($agentId);
        array_unshift($brr,DB::table('agent') -> where(['id'=>$agentId]) -> first());
        foreach ($brr as $v){
            $agent[$v['id']] = $v;
        }
        return $agent;
    }

    //根据path处理代理商名称
    public function agentInfo($agentId){
        //查询父级代理商path
        $path = DB::table('agent') -> select('path') -> where(['id'=>$agentId]) -> first();
        $len = substr_count($path['path'],',');
        $agentInfo = $this -> allAgent($agentId);
        foreach ($agentInfo as $k=>$v){
            $agentInfo[$k]['name'] = str_repeat('--',substr_count($v['path'],',')-$len).$v['name'];
        }
        return $agentInfo;
    }
    /*************代理商信息处理域*************/
}
